package com.bluetrum.devicemanager.cmd.request;

import androidx.annotation.Nullable;

import java.util.HashMap;
import java.util.Map;

public class MultipointRequest extends TlvRequest {

    public static final byte MULTIPOINT_STATUS      = 1;
    public static final byte MULTIPOINT_CONNECT     = 2;
    public static final byte MULTIPOINT_DISCONNECT  = 3;
    public static final byte MULTIPOINT_UNPAIR      = 4;

    private final Boolean enable;
    private final byte[] addressToConnect;
    private final byte[] addressToDisconnect;
    private final byte[] addressToUnpair;

    private MultipointRequest(@Nullable Boolean enable,
                              @Nullable byte[] addressToConnect,
                              @Nullable byte[] addressToDisconnect,
                              @Nullable byte[] addressToUnpair) {
        super(COMMAND_MULTIPOINT);
        this.enable = enable;
        this.addressToConnect = addressToConnect;
        this.addressToDisconnect = addressToDisconnect;
        this.addressToUnpair = addressToUnpair;

        // invoke before use getPreGeneratedPayload()
        generatePayload();
    }

    public static MultipointRequest enableRequest(boolean enable) {
        return new MultipointRequest(enable, null, null, null);
    }

    // 关闭功能的同时断开某台设备
    public static MultipointRequest disableRequest(byte[] addressToDisconnect) {
        return new MultipointRequest(false, null, addressToDisconnect, null);
    }

    public static MultipointRequest connectRequest(byte[] address) {
        return new MultipointRequest(null, address, null, null);
    }

    public static MultipointRequest disconnectRequest(byte[] address) {
        return new MultipointRequest(null, null, address, null);
    }

    public static MultipointRequest unpairRequest(byte[] address) {
        return new MultipointRequest(null, null, null, address);
    }

    @Override
    protected Map<Byte, Object> getTlvObjectMap() {
        return new HashMap<Byte, Object>(){{
            put(MULTIPOINT_STATUS, enable);
            put(MULTIPOINT_CONNECT, obfuscateAddress(addressToConnect));
            put(MULTIPOINT_DISCONNECT, obfuscateAddress(addressToDisconnect));
            put(MULTIPOINT_UNPAIR, obfuscateAddress(addressToUnpair));
        }};
    }

    @Nullable
    private byte[] obfuscateAddress(@Nullable byte[] address) {
        if (address == null) return null;

        byte[] result = new byte[6];
        for (int i = 0; i < address.length; i++) {
            result[i] = (byte) ((address[i] & 0xFF) ^ 0xAD);
        }
        return result;
    }

    @Override
    public byte[] getPayload() {
        return getPreGeneratedPayload();
    }
}
